package com.taobao.freetest.ui.editer;

import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.preference.FieldEditorPreferencePage;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.widgets.Composite;

import com.taobao.freetest.Constants;
import com.taobao.freetest.util.LogUtils;
import com.taobao.freetest.util.UserPreferenceUtils;

public class UserEditor extends AbstractStringButtonFieldEditor {

	private boolean ok = true;
	private FieldEditorPreferencePage preferencePage;
	
	public UserEditor(Composite parent,FieldEditorPreferencePage preferencePage) {
		super(parent);
		this.preferencePage = preferencePage;
	}
	
	@Override
	protected String changePressed() {
		try {
			check();
			getPage().setMessage("Valid user name  ", IMessageProvider.INFORMATION);
			ok = true;
			preferencePage.setValid(true);
		} catch (Throwable e) {
			showErrorMessage(e.getMessage());
			ok = false;
			preferencePage.setValid(false);
			LogUtils.error(e.getMessage(), e);
		}
		return null;
	}
	
	private void check() {
		if (getStringValue() != null && !"".equals(getStringValue().trim())) {
			UserPreferenceUtils.checkUserName(getStringValue());
		}
	}
	
	@Override
	public boolean isOk() {
		return this.ok ;
	}
	
	
	
	@Override
	protected String getDefaultValue(){
		String userName = System.getProperties().getProperty("user.name");
		if(userName.contains(".")){
			userName = userName.substring(0, userName.indexOf("."));
		}
		return userName;
	}
	
	@Override
	protected FocusListener getFocusListerner() {
		return new FocusListener() {
			public void focusGained(FocusEvent e) {
			}

			public void focusLost(FocusEvent e) {
				if (isValid()) {
					getPage().setMessage(null);
				}
			}

		};
	}
	
	@Override
	public String getLabelText() {
		return "User Name";
	}
	
	@Override
	protected String getName() {
		return Constants.PREF_FREETEST_USER_NAME;
	}
}
